﻿using HongYeSystemWebApi.Templet.Entity.ApiResult;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;

namespace HongYeSystemWebApi.Templet.Core
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        /// <summary>
        /// 异常统一处理 并记录错误消息 返回至前端
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            var hashCode = context.GetHashCode();

            //Thread.Sleep(2000);
            //记录请求Url（context.HttpContext.Request.Path.Value） 传入参数 客户端IP 
            //判断请求类型 若为Get 则参数在QueryString context.HttpContext.Request.QueryString.Value
            // Post 参数在Body
            var method = context.HttpContext.Request.Method;
            var path = context.HttpContext.Request.Path.Value;
            var data = string.Empty;
            if (method == "GET")
            {
                data = context.HttpContext.Request.QueryString.Value;
            }
            else if (method == "POST")
            {
                 //StreamReader reader = new StreamReader(context.HttpContext.Request.Body);
                 //data = reader.ReadToEnd();
                //Post入参尚未抓到
                data = "Post";
            }
            var content = JsonConvert.SerializeObject(new
            {
                HashCode = hashCode,
                context.Exception.Message,
                StackTrace = context.Exception.StackTrace.Trim(),
                Method = method,
                Path = path,
                Data = data
            });

            Console.WriteLine(content);
            LogHelp.LogError(content);
            JsonResult json = new JsonResult(new ApiResult {  StatusCode = 500, Message = context.Exception.Message,  Status = false });
            context.Result = json;
        }
    }
}
